import java.util.Stack;

/**
* @description: 1003. 检查替换后的词是否有效
* @author hewei
* @date 2022/10/4 16:35
* @version 1.0
*/

public class IsValid2 {

    public boolean isValid1(String s) {
        int n = s.length();
        if (n % 3 != 0) return false;
        while (true) {
            int index = s.indexOf("abc");
            if (index == -1) {
                return s.equals("");
            }
            s = s.substring(0, index) + s.substring(index + 3);
        }
    }

    public boolean isValid(String s) {
        char[] chars = s.toCharArray();
        Stack<Character> stack = new Stack<>();
        for (char c : chars) {
            if (c != 'c') {
                stack.push(c);
            } else {
                if (stack.size() < 2) return false;
                Character pop1 = stack.pop();
                Character pop2 = stack.pop();
                if (pop1 != 'b' || pop2 != 'a') return false;
            }
        }
        return stack.isEmpty();
    }
}
